<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="本节的目的是根据-cp命令指定的class路径以及后面的ClassName,找到对应的class文件,然后简单的打印出该 class 文件的字节码.完整源码classpath包中">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(3)-搜索class文件">
<meta property="og:url" content="https://zachaxy.github.io/2017/05/08/手写JVM系列-3-搜索class文件/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="本节的目的是根据-cp命令指定的class路径以及后面的ClassName,找到对应的class文件,然后简单的打印出该 class 文件的字节码.完整源码classpath包中">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.304Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(3)-搜索class文件">
<meta name="twitter:description" content="本节的目的是根据-cp命令指定的class路径以及后面的ClassName,找到对应的class文件,然后简单的打印出该 class 文件的字节码.完整源码classpath包中">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/05/08/手写JVM系列-3-搜索class文件/">





  <title>手写JVM系列(3)-搜索class文件 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/08/手写JVM系列-3-搜索class文件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(3)-搜索class文件</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-08T15:01:12+08:00">
                2017-05-08
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,477
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <blockquote>
<p>本节的目的是根据<code>-cp</code>命令指定的class路径以及后面的<code>ClassName</code>,找到对应的class文件,然后简单的打印出该 class 文件的字节码.完整源码<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">classpath包中</a></p>
</blockquote>
<a id="more"></a>

<h1 id="关于classpath"><a href="#关于classpath" class="headerlink" title="关于classpath"></a>关于classpath</h1><p><code>Java</code>虚拟机规范并没有规定虚拟机应该从哪里寻找类，因此不同的虚拟机实现可以采用不同的方法。Oracle的Java虚拟机实现根据类路径（class path）来搜索类。按照搜索的先后顺序,类路径分为以下三部分:</p>
<ul>
<li>启动类路径(bootstrap classpath):默认对应jre\lib目录，Java标准库(大部分在rt.jar里)位于该路径</li>
<li>扩展类路径(extension classpath):默认对应jre\lib\ext目录，使用Java扩展机制的类位于这个路径</li>
<li>用户类路径(user classpath):自己实现的类，以及第三方类库则位于用户类路径</li>
</ul>
<blockquote>
<p>这里特别说一下:用户类路径的<strong>默认值</strong>就是当前目录,这也是平时我们配置Java开发环境时,网上很多教程会说要添加一个<code>classpath</code>变量,并将其变量值设置为 <code>.</code> (表示当前路径),其实这个根本没有必要,因为虚拟机默认是在当前路径下寻找class文件的.所以在刚开始学习Java编程时,使用文本编辑器写代码,只需要配置一个<code>JAVA_HOME</code>即可,如果是用<code>IDE</code>,那么恐怕连<code>JAVA_HOME</code>都不需要,只要你安装了<code>JDK</code>,在<code>IDE</code>中配置其路径即可,至于<code>classpath</code>,都是由<code>IDE</code>的脚本自动写好的,不同的<code>IDE</code>有自己的路径,我们只需要在<code>IDE</code>中写好代码,点击运行即可.</p>
</blockquote>
<p>我们这里编写的<code>JVM</code>是脱离<code>IDE</code>的,所以不能指望<code>IDE</code>来帮我们寻找路径,经过上面的分析,一个想法就是配置一个<code>classpath</code>的环境变量,将所有的<code>class</code>文件都丢到这个路径下,但是这样做并不灵活,更好的办法是给<code>java</code>命令传递<code>-classpath</code>（或简写为-cp）选项。<code>-classpath/-cp</code>选项的优先级更高，可以覆盖<code>CLASSPATH环境变量</code>。</p>
<h2 id="java命令中的classpath-选项"><a href="#java命令中的classpath-选项" class="headerlink" title="java命令中的classpath 选项"></a>java命令中的classpath 选项</h2><p> <code>-classpath/-cp</code>选项既可以指定目录，也可以指定<code>JAR</code>文件或者<code>ZIP</code>文件</p>
<h2 id="添加指向JDK启动类路径"><a href="#添加指向JDK启动类路径" class="headerlink" title="添加指向JDK启动类路径"></a>添加指向JDK启动类路径</h2><p><code>Java</code>虚拟机将使用JDK的启动类路径来寻找和加载<code>Java</code>标准库中的类，因此需要某种方式指定<code>jre</code>目录的位置。命令行选项是个不错的选择，所以增加一个非标准选<code>-Xjre</code>选项。但是这一选项并不是必须的，目前已经实现了读取<code>JAVA_HOME</code>来寻找启动类路径的功能，所以<code>-Xjre</code>选项是在没有配置<code>JAVA_HOME</code>环境变量的情况下，使用的。如果本地机器上有该环境变量，则无需指定<code>-Xjre</code></p>
<p>注意这个选项的效果类似于<code>-classpath</code>,只不过这个选项是我们为了实现<code>JVM</code>自己添加的选项,并不是<code>java</code>自带的,其功能是指向<strong><code>JDK</code>启动类路径</strong>,而<code>-cp</code>是指定<strong>用户类路径</strong>.</p>
<p>但是不管怎样,最终的结果都是根据其执行的路径和后面所跟的类名,找到对应的<code>class</code>文件</p>
<h1 id="代码编写"><a href="#代码编写" class="headerlink" title="代码编写"></a>代码编写</h1><blockquote>
<p>搜索class文件所实现的功能源码都在项目的<a href="https://github.com/zachaxy/JVM/tree/master/Java/src/classpath" target="_blank" rel="noopener">classpath包</a>下.</p>
</blockquote>
<h2 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h2><p>首先考虑一下在命令行使用时的可能的场景:</p>
<ol>
<li>直接指定路径,后面跟类名:<code>java -cp aaa/bbb/ccc  ddd  arg1  arg2</code></li>
<li>指定类所在的jar文件的路径,后面跟类名:<code>java -cp aaa/bbb/ccc.jar  ddd arg1  arg2</code></li>
<li>指定一个模糊路径,后面跟类名:<code>java -cp aaa/bbb/*  ddd  arg1  arg2</code></li>
<li>指定若干个路径,后面跟类名(指定的类存在指定的某一条路径中,如果都存在那么以第一条为准):<code>java -cp aaa1/bbb/ccc;aaa2/bbb/ccc;aaa3/bbb/ccc;  ddd  arg1  arg2</code></li>
</ol>
<h2 id="抽象类-Entry"><a href="#抽象类-Entry" class="headerlink" title="抽象类 Entry"></a>抽象类 Entry</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Entry</span> </span>&#123;</span><br><span class="line">    <span class="comment">//路径分隔符,在window下,使用 ; 分割开的  在Unix/Linux下使用: 分割开的</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String pathListSeparator = System.getProperty(<span class="string">"os.name"</span>).contains(<span class="string">"Windows"</span>) ? <span class="string">";"</span> : <span class="string">":"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 负责寻找和加载class文件</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> className class文件的相对路径，路径之间用斜线 / 分隔，文件名有.class后缀</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">abstract</span> <span class="keyword">byte</span>[] readClass(String className) <span class="keyword">throws</span> IOException;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 返回className的字符串表示形式;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">abstract</span> String <span class="title">printClassName</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 工厂方法,根据传入的path的形式不同,</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> path 命令行得到的路径字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 创建具体的Entry</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">static</span> Entry <span class="title">createEntry</span><span class="params">(String path)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (path != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (path.contains(pathListSeparator)) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> CompositeEntry(path, pathListSeparator);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (path.contains(<span class="string">"*"</span>)) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> WildcardEntry(<span class="string">""</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (path.contains(<span class="string">".jar"</span>) || path.contains(<span class="string">".JAR"</span>) || path.contains(<span class="string">".zip"</span>) || path.contains(<span class="string">""</span> +</span><br><span class="line">                    <span class="string">".ZIP"</span>)) &#123;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> ZipJarEntry(path);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> DirEntry(path);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="具体实现类"><a href="#具体实现类" class="headerlink" title="具体实现类"></a>具体实现类</h2><ul>
<li>DirEntry</li>
<li>ZipJarEntry</li>
<li>WildcardEntry</li>
<li>CompositeEntry</li>
</ul>
<p>这四个类是<code>Entry</code>的具体实现类,分别对应使用场景中的四种情况,下面会分析四种情况所要解决的问题,这里只贴出<code>DirEntry</code>的代码,先于篇幅原因,其它三种情况的具体实现,请查看本项目<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">源码</a></p>
<h3 id="DirEntry"><a href="#DirEntry" class="headerlink" title="DirEntry"></a>DirEntry</h3><p>这应该是最简单的一种使用场景了,构造方法中传入的字符串表示目录形式的类路径,这里拿到的直接就是指定的路径,那么先判断该路径是否存在,如果存在,那么和<code>className</code>拼接起来,使用<code>IO</code>流读取其中的字节码,并返回.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DirEntry</span> <span class="keyword">extends</span> <span class="title">Entry</span> </span>&#123;</span><br><span class="line">    String absDir;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DirEntry</span><span class="params">(String path)</span> </span>&#123;</span><br><span class="line">        File dir = <span class="keyword">new</span> File(path);</span><br><span class="line">        <span class="keyword">if</span> (dir.exists()) &#123;</span><br><span class="line">            absDir = dir.getAbsolutePath();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">byte</span>[] readClass(String className) <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(absDir, className);</span><br><span class="line">        <span class="keyword">byte</span>[] temp = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        BufferedInputStream in = <span class="keyword">null</span>;</span><br><span class="line">        ByteArrayOutputStream out = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        in = <span class="keyword">new</span> BufferedInputStream(<span class="keyword">new</span> FileInputStream(file));</span><br><span class="line">        out = <span class="keyword">new</span> ByteArrayOutputStream(<span class="number">1024</span>);</span><br><span class="line">        <span class="keyword">int</span> size = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span> ((size = in.read(temp)) != -<span class="number">1</span>) &#123;</span><br><span class="line">            out.write(temp, <span class="number">0</span>, size);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (in != <span class="keyword">null</span>) &#123;</span><br><span class="line">            in.close();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (out != <span class="keyword">null</span>) &#123;</span><br><span class="line">            out.close();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> out.toByteArray();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function">String <span class="title">printClassName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> absDir;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="ZipJarEntry"><a href="#ZipJarEntry" class="headerlink" title="ZipJarEntry"></a>ZipJarEntry</h3><p>这种使用场景是指定了一个<code>zip文件</code>或者<code>jar包</code>的情况,那么需要解决的问题是如何拿到压缩文件中的文件,这里主要使用了<code>java.util.zip</code>包下的类来拿到文件,使用zipFile来读取文件和读取普通的文件夹类似,这里只管把zip文件当成文件夹就好</p>
<p>这里有一点要注意的是:</p>
<p>如果是<code>zip</code>文件,在获取<code>ZipEntry</code>的时候<code>ZipEntry ze = zipFile.getEntry(zipName + &quot;/&quot; + className)</code></p>
<p>如果是<code>jar</code>包,在获取<code>ZipEntry</code>的时候,<code>ZipEntry ze = zipFile.getEntry(className)</code></p>
<h3 id="WildcardEntry"><a href="#WildcardEntry" class="headerlink" title="WildcardEntry"></a>WildcardEntry</h3><p>这种使用场景是指定了一个形如<code>aa/bb/*</code>的路径,这种路径表明我们的<code>class</code>文件在<code>aa/bb/</code>路径下的<code>jar</code>包中,所以我们只要遍历该路径下的所有以<code>.jar</code>结尾的文件,然后调用<code>ZipJarEntry</code>的实现方法,即可以获得字节码.</p>
<h3 id="CompositeEntry"><a href="#CompositeEntry" class="headerlink" title="CompositeEntry"></a>CompositeEntry</h3><p>这种使用场景是包含多个路径的情况,(eg:a1/b1/c1;a2/b2/c2;a3/b3/c3),那么遇到这种情况,需要将字符串分割成不同的子串,注意分割符在不同的系统下是不同的,这里仅仅实现<code>windows</code>,其它情况下视为<code>unix</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String pathListSeparator = System.getProperty(<span class="string">"os.name"</span>).contains(<span class="string">"Windows"</span>) ? <span class="string">";"</span> : <span class="string">":"</span>;</span><br></pre></td></tr></table></figure>

<p>当然分成的子串分别对应一个<code>DirEntry</code>,再调用<code>DirEntry</code>的方法来获取字节码.</p>
<h2 id="classpath对外的统一使用接口"><a href="#classpath对外的统一使用接口" class="headerlink" title="classpath对外的统一使用接口"></a>classpath对外的统一使用接口</h2><p>上面我们已经实现了对于 classpath 路径的解析,这里在进行一步封装,提供一个对外的统一接口.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassPath</span> </span>&#123;</span><br><span class="line">    <span class="comment">//分别存放三种类路径</span></span><br><span class="line">    Entry bootClasspath;</span><br><span class="line">    Entry extClasspath;</span><br><span class="line">    Entry userClasspath;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//parse()函数使用 -Xjre 选项解析启动类路径和扩展类路径</span></span><br><span class="line">    <span class="comment">// 使用-classpath/-cp选项解析用户类路径</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ClassPath</span><span class="params">(String jreOption, String cpOption)</span> </span>&#123;</span><br><span class="line">        parseBootAndExtClasspath(jreOption);</span><br><span class="line">        parseUserClasspath(cpOption);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//这里参数传进来的是: C:\Program Files\Java\jdk1.8.0_20\jre</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">parseBootAndExtClasspath</span><span class="params">(String jreOption)</span> </span>&#123;</span><br><span class="line">        String jreDir = getJreDir(jreOption);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//可能出现的情况是: jre/lib/*</span></span><br><span class="line">        String jreLibPath = jreDir + File.separator + <span class="string">"lib"</span> + File.separator + <span class="string">"*"</span>;</span><br><span class="line">        bootClasspath = <span class="keyword">new</span> WildcardEntry(jreLibPath);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//可能出现的情况是: jre/lib/ext/*</span></span><br><span class="line">        String jreExtPath = jreDir + File.separator + <span class="string">"lib"</span> + File.separator + <span class="string">"ext"</span> + File.separator + <span class="string">"*"</span>;</span><br><span class="line">        extClasspath = <span class="keyword">new</span> WildcardEntry(jreExtPath);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function">String <span class="title">getJreDir</span><span class="params">(String jreOption)</span> </span>&#123;</span><br><span class="line">        File jreFile;</span><br><span class="line">        <span class="keyword">if</span> (jreOption != <span class="keyword">null</span> &amp;&amp; jreOption != <span class="string">""</span>) &#123;</span><br><span class="line">            jreFile = <span class="keyword">new</span> File(jreOption);</span><br><span class="line">            <span class="keyword">if</span> (jreFile.exists()) &#123;</span><br><span class="line">                <span class="keyword">return</span> jreOption;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        jreFile = <span class="keyword">new</span> File(<span class="string">"jre"</span>);</span><br><span class="line">        <span class="keyword">if</span> (jreFile.exists()) &#123;</span><br><span class="line">            <span class="keyword">return</span> jreFile.getAbsolutePath();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        String java_home = System.getenv(<span class="string">"JAVA_HOME"</span>);</span><br><span class="line">        <span class="keyword">if</span> (java_home != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> java_home + File.separator + <span class="string">"jre"</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Can not find jre folder!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">parseUserClasspath</span><span class="params">(String cpOption)</span> </span>&#123;</span><br><span class="line">        userClasspath = Entry.createEntry(cpOption);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] readClass(String className) &#123;</span><br><span class="line">        className = className + <span class="string">".class"</span>;</span><br><span class="line">        <span class="keyword">byte</span>[] data;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            data = bootClasspath.readClass(className);</span><br><span class="line">            <span class="keyword">if</span> (data != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> data;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            data = extClasspath.readClass(className);</span><br><span class="line">            <span class="keyword">if</span> (data != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> data;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            data = userClasspath.readClass(className);</span><br><span class="line">            <span class="keyword">if</span> (data != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> data;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"can't find class!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userClasspath.printClassName();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>构造方法:传入解析到的 <code>-Xjre</code>来的路径和<code>-cp</code>的路径,当然在<code>Cmd</code>类中,这两个路径的初始值都是空字符串,而不是<code>null</code>,然后根据二者的值进行解析</p>
<p>之前也说过寻找 class 文件是由优先级的,依次是:<code>bootClasspath</code>-&gt; <code>extClasspath</code> -&gt;  <code>userClasspath</code>那么我们怎么实现这个加载顺序呢? </p>
<p>首先:在<code>Cmd</code>类中,这两个路径的初始值是:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String XjreOption = <span class="string">""</span>;</span><br><span class="line">String cpOption = <span class="string">""</span>;</span><br></pre></td></tr></table></figure>

<p>这里优先使用用户输入的 -Xjre 选项作为 jre 目录。如果没有输入该选项，则在当前目录下寻找 jre 目录。如果找不到，尝试使用 JAVA_HOME 环境变量。最终返回<code>bootClasspath</code>和<code>extClasspath</code>.</p>
<p>然后再根据 <code>-cp</code>的值得到一个<code>userClasspath</code>,然后再根据这三个<code>Entry</code>的顺序来加载类文件,一旦加载到,直接返回。</p>
<p>最终,使用<code>readClass</code>()方法就可以返回我们要加载的类文件字节数组。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/05/08/手写JVM系列-3-搜索class文件/" title="手写JVM系列(3)-搜索class文件">https://zachaxy.github.io/2017/05/08/手写JVM系列-3-搜索class文件/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/05/07/手写JVM系列-2-参数解析/" rel="next" title="手写JVM系列(2)-参数解析">
                <i class="fa fa-chevron-left"></i> 手写JVM系列(2)-参数解析
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/05/09/手写JVM系列-4-分析class文件/" rel="prev" title="手写JVM系列(4)-分析class文件">
                手写JVM系列(4)-分析class文件 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#关于classpath"><span class="nav-number">1.</span> <span class="nav-text">关于classpath</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#java命令中的classpath-选项"><span class="nav-number">1.1.</span> <span class="nav-text">java命令中的classpath 选项</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#添加指向JDK启动类路径"><span class="nav-number">1.2.</span> <span class="nav-text">添加指向JDK启动类路径</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#代码编写"><span class="nav-number">2.</span> <span class="nav-text">代码编写</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用场景"><span class="nav-number">2.1.</span> <span class="nav-text">使用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#抽象类-Entry"><span class="nav-number">2.2.</span> <span class="nav-text">抽象类 Entry</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#具体实现类"><span class="nav-number">2.3.</span> <span class="nav-text">具体实现类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#DirEntry"><span class="nav-number">2.3.1.</span> <span class="nav-text">DirEntry</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ZipJarEntry"><span class="nav-number">2.3.2.</span> <span class="nav-text">ZipJarEntry</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#WildcardEntry"><span class="nav-number">2.3.3.</span> <span class="nav-text">WildcardEntry</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CompositeEntry"><span class="nav-number">2.3.4.</span> <span class="nav-text">CompositeEntry</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#classpath对外的统一使用接口"><span class="nav-number">2.4.</span> <span class="nav-text">classpath对外的统一使用接口</span></a></li></ol></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
